#!/bin/bash 
#scripts for tcp status 

metric=$1

function SYNRECV { 
/usr/sbin/ss -ant | awk '{++s[$1]} END {for(k in s) print k,s[k]}' | grep 'SYN-RECV' | awk '{print $2}'
} 
function ESTAB { 
/usr/sbin/ss -ant | awk '{++s[$1]} END {for(k in s) print k,s[k]}' | grep 'ESTAB' | awk '{print $2}'
} 
function FINWAIT1 { 
/usr/sbin/ss -ant | awk '{++s[$1]} END {for(k in s) print k,s[k]}' | grep 'FIN-WAIT-1' | awk '{print $2}'
} 
function FINWAIT2 { 
/usr/sbin/ss -ant | awk '{++s[$1]} END {for(k in s) print k,s[k]}' | grep 'FIN-WAIT-2' | awk '{print $2}'
} 
function TIMEWAIT { 
/usr/sbin/ss -ant | awk '{++s[$1]} END {for(k in s) print k,s[k]}' | grep 'TIME-WAIT' | awk '{print $2}'
} 
function LASTACK { 
/usr/sbin/ss -ant | awk '{++s[$1]} END {for(k in s) print k,s[k]}' | grep 'LAST-ACK' | awk '{print $2}'
} 
function LISTEN { 
/usr/sbin/ss -ant | awk '{++s[$1]} END {for(k in s) print k,s[k]}' | grep 'LISTEN' | awk '{print $2}'
}
function CLOSED {
/usr/sbin/ss -ant | awk '{++s[$1]} END {for(k in s) print k,s[k]}' | grep 'CLOSED' | awk '{print $2}'
}
function SYNSENT {
/usr/sbin/ss -ant | awk '{++s[$1]} END {for(k in s) print k,s[k]}' | grep 'SYN_SENT' | awk '{print $2}'
}
 
case $metric in
   closed)
          output=$(CLOSED)
          if [ X"$output" == X"" ];then
             echo 0
          else
             echo $output
          fi
        ;;
   listen)
          output=$(LISTEN)
          if [ X"$output" == X"" ];then
             echo 0
          else
             echo $output
          fi
        ;;
   synrecv)
          output=$(SYNRECV)
          if [ X"$output" == X"" ];then
             echo 0
          else
             echo $output
          fi
        ;;
   synsent)
          output=$(SYNSENT)
          if [ "X$output" == X"" ];then
             echo 0
          else
             echo $output
          fi
        ;;
   established)
          output=$(ESTAB)
          if [ "X$output" == X"" ];then
             echo 0
          else
             echo $output
          fi
        ;;
   timewait)
          output=$(TIMEWAIT)
          if [ "X$output" == X"" ];then
             echo 0
          else
             echo $output
          fi
        ;;
     finwait1)
          output=$(FINWAIT1)
          if [ "X$output" == X"" ];then
             echo 0
          else
             echo $output
          fi
        ;;
     finwait2)
          output=$(FINWAIT2)
          if [ "X$output" == X"" ];then             
             echo 0
          else
             echo $output
          fi
        ;;
   *)
   echo -e "\033[41;36m Usage: $0 {established|synsent|synrecv|listen|closed|timewait|finwait2|finwait1} \033[0m"
   echo -e "\033[40;33mthe server now tcp status \033[0m"
   /usr/sbin/ss -ant | awk '{++s[$1]} END {for(k in s) print k,s[k]}'
   esac